﻿function TypeSelection(JavascriptId)
{
	this.Answer=null;
	this.Data=null;
	this.onchange=null;
	this.customValidator=true;
	this.Required = false;
	this.Group=null;
	this.PropertyName = null;
	this.DescriptionField = 'Description';


	this.GetPopup=function(l){
		var pid='popup'+l;
		if(this[pid]==null)
		{
			$('body').append('<div class="PopupMenuPanel" id="' + pid + '"></div>');
			
			if(l)
			{
				this[pid]=new PopupMenu(pid, -10, 5, 'tr+');
				this[pid].SetParent(this['popup'+(l-1)]);
			}
			else
				this[pid]=new PopupMenu(pid, 0, -1, 'br');
		}
		return this[pid];
	}
	this.Find=function(id, l){
		if(!l)
			l=this.Data;
		for(var i=0;i<l.length;i++)
		{
			if(l[i].Id==id)
				return l[i];
			var n=this.Find(id, l[i].Children);
			if(n)
				return n;
		}
		return null;
	}
	this.GetItems=function(id){
		if(!id)
			return this.Data;
		var n=this.Find(id);
		return n.Children;
	}
	this.Show=function(src, l, pid){
		if(src==null)
			src=el(JavascriptId);
		if(!l)
			l=0;
		var p=this.GetPopup(l);
		var tl=this.GetItems(pid);
		if(tl==null||tl.length==0)
			return;
		var h='';
		h+='<div class="PopupMenu">';
		var sl= tl.sort(function(a,b){
			if(a[this.DescriptionField]<b[this.DescriptionField])
				return -1;
			if(a[this.DescriptionField]>b[this.DescriptionField])
				return 1;
			return 0;
		});
		for(var i in sl)
		{
			var g=sl[i];
			if(pid&&g.ParentId!=(pid+''))
				continue;
			if (g.Children && g.Children.length)
				h+='<div class="MenuItem ArrowRight" onmouseover="'+JavascriptId+'.Show(this, '+(l+1)+', '+g.Id+');">'+g[this.DescriptionField]+'</div>';
			else
				h+='<div class="MenuItem" onclick="'+JavascriptId+'.Select('+g.Id+');">'+g[this.DescriptionField]+'</div>';
		}
		h+='</div>';
		p.Hide();
		p.ShowFromNewSource(src, h);
	}
	this.Select=function(id){
		this.SetAnswer(id);
		if(this.onchange)
			eval(this.onchange+'('+id+');');
	}
	this.IsValid = function() {
		var tvid=JavascriptId+'Validator';
		var tv=eval(tvid);
		tv.Hide();
		if(this.Required&&!this.Answer)
		{
			var html = '<img src="resource.axd?Failure.gif" style="margin-left: 5px;margin-top:0px;" title="This is a required field." id="' + JavascriptId + '.Val" />';
			$('#'+tvid).css('background', 'transparent');
			tv.ShowFromNewSource(el(JavascriptId), html);
			return false;
		}
		return true;
	}
	this.GetAnswer=function(){
		return this.Answer;
	}
	this.GetDescription = function(id) {
		var s = '';
		var t = this.Find(id);
		if (t != null) {
			var p = this.Find(t.ParentId);
			while (p) {
				s = p[this.DescriptionField] + ' / ' + s;
				p = this.Find(p.ParentId);
			}
			s += t[this.DescriptionField];
		}
		return s;
	}
	this.SetAnswer=function(a){
		this.Answer = a;
		var d = this.GetDescription(a)
		if(d&&d!='')
			$('#'+JavascriptId).html(d);
	}
	if(window.Validators)
		Validators[Validators.length]=this;
}
